package com.zhihaoliang.coroutine.buss.excep.func

import com.zhihaoliang.coroutine.util.log
import kotlinx.coroutines.*

/**
 * @author 支豪亮
 * @date 2022/10/28 11:15
 * @des 异常处理
 */
object ExceptionPropagation {

    @OptIn(DelicateCoroutinesApi::class)
    fun propagationException(mainScope:CoroutineScope) = mainScope.launch {
        val deferred = GlobalScope.async { // root coroutine with async
            log("Throwing exception from async")
            throw ArithmeticException() // Nothing is printed, relying on user to call await
        }
        try {
            deferred.await()
            log("Unreached")
        } catch (e: ArithmeticException) {
            log("Caught ArithmeticException")
        }

        val job = try {
           GlobalScope.launch { // root coroutine with launch
                log("Throwing exception from launch")
                throw IndexOutOfBoundsException() // Will be printed to the console by Thread.defaultUncaughtExceptionHandler
            }
        }catch(e:Exception) {
            log("Throwing exception from launch")
            null
        }

        job?.join()
        log("Joined failed job")

    }
}